package com.wgh.gateway.controller;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关熔断降级处理控制器
 */
@RestController
public class FallbackController {
    
    /**
     * 商品服务熔断降级处理
     */
    @RequestMapping("/fallback/product")
    public Mono<String> productFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "商品服务");
    }
    
    /**
     * 订单服务熔断降级处理
     */
    @RequestMapping("/fallback/order")
    public Mono<String> orderFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "订单服务");
    }
    
    /**
     * 购物车服务熔断降级处理
     */
    @RequestMapping("/fallback/cart")
    public Mono<String> cartFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "购物车服务");
    }
    
    /**
     * 支付服务熔断降级处理
     */
    @RequestMapping("/fallback/pay")
    public Mono<String> payFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "支付服务");
    }
    
    /**
     * 库存服务熔断降级处理
     */
    @RequestMapping("/fallback/inventory")
    public Mono<String> inventoryFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "库存服务");
    }
    
    /**
     * 搜索服务熔断降级处理
     */
    @RequestMapping("/fallback/search")
    public Mono<String> searchFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "搜索服务");
    }
    
    /**
     * 用户服务熔断降级处理
     */
    @RequestMapping("/fallback/user")
    public Mono<String> userFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "用户服务");
    }
    
    /**
     * 管理后台服务熔断降级处理
     */
    @RequestMapping("/fallback/admin")
    public Mono<String> adminFallback(ServerWebExchange exchange) {
        return handleFallback(exchange, "管理后台服务");
    }
    
    /**
     * 统一的熔断降级处理方法
     */
    private Mono<String> handleFallback(ServerWebExchange exchange, String serviceName) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethod().toString();
        
        // 设置响应状态
        exchange.getResponse().setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        
        // 记录熔断信息
        String errorMsg = String.format("{\"code\":503,\"message\":\"%s暂时不可用，请稍后再试\",\"path\":\"%s\",\"method\":\"%s\"}", 
                serviceName, path, method);
        
        return Mono.just(errorMsg);
    }
    
    /**
     * 初始化全局的网关回调
     */
    static {
        GatewayCallbackManager.setBlockHandler((exchange, t) -> {
            String errorMsg = "{\"code\":503,\"message\":\"服务繁忙，请稍后再试\",\"data\":null}";
            exchange.getResponse().setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            exchange.getResponse().writeWith(Mono.just(
                    exchange.getResponse().bufferFactory().wrap(errorMsg.getBytes())));
            return Mono.empty();
        });
    }
}